package com.icesoft.xsnow.oauth.endpoint;

import com.icesoft.xsnow.framework.api.reponses.R;
import com.icesoft.xsnow.framework.api.reponses.SuccessR;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.endpoint.FrameworkEndpoint;
import org.springframework.security.oauth2.provider.token.ConsumerTokenServices;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @program: xsnow
 * @description: 注销TOKEN
 * @author: xuefeng.gao
 * @create: 2019-05-30 15:36
 **/
@FrameworkEndpoint
@Slf4j
public class RevokeTokenEndpoint  {

    @Autowired
    ConsumerTokenServices consumerTokenServices;



    @RequestMapping(method = RequestMethod.DELETE, value = "/oauth/token/{access_token}")
    @ResponseBody
    public R revokeTokenRst(@PathVariable String access_token, HttpServletRequest request,HttpServletResponse response) {
        //1. 清除TOKEN
        consumerTokenServices.revokeToken(access_token);

        //2. 清除该Request的session
        Assert.notNull(request, "HttpServletRequest required");
        HttpSession session = request.getSession(false);
        if (session != null) {
            log.debug("Invalidating session: " + session.getId());
            session.invalidate();
        }

        //3.清除Authentication
        SecurityContext context = SecurityContextHolder.getContext();
        context.setAuthentication(null);
        SecurityContextHolder.clearContext();
        return SuccessR.success(response,"Token已成功注销");
    }

}
